package com.baymax.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baymax.constant.Constant;
import com.baymax.entity.Address;
import com.baymax.entity.User;
import com.baymax.entity.dto.UserDTO;
import com.baymax.entity.vo.UserVO;
import com.baymax.exception.GlobalException;
import com.baymax.mapper.UserMapper;
import com.baymax.service.AddressService;
import com.baymax.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户 服务
 *
 * @author baymax
 * @date 2023-03-17 14:49
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 记录用户新增、编辑、删除操作，用于撤回使用
     */
    private final static Map<String, Object> recordLastHandleMap = new HashMap<>();

    private final AddressService addressService;

    @Override
    public IPage<UserVO> pageUser(UserDTO userDTO, Page page) {
        return baseMapper.pageUser(page, userDTO);
    }

    @Override
    public UserVO detail(Integer userId) {
        System.out.println(recordLastHandleMap.toString());
        return baseMapper.detail(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addUserInfo(UserDTO userDTO) {
        validUniquePhoneNumber(userDTO.getUserId(), userDTO.getPhoneNumber());
        Address address = new Address();
        address.setProvince(userDTO.getProvince());
        address.setCity(userDTO.getCity());
        address.setDistrict(userDTO.getDistrict());
        address.setDetailAddress(userDTO.getDetailAddress());
        address.setAddressValue(userDTO.getAddressValue());
        if (!addressService.save(address)) {
            throw new GlobalException("新增用户地址失败");
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setAddressId(address.getAddressId());
        if (!save(user)) {
            throw new GlobalException("新增用户信息失败");
        }
        // 记录当前的操作，用于撤销使用
        recordLastHandleMap.put(Constant.addHandle, user);
        recordLastHandleMap.remove(Constant.editHandle);
        recordLastHandleMap.remove(Constant.delHandle);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean editUserInfo(UserDTO userDTO) {
        if (userDTO.getUserId() == null) {
            throw new GlobalException("用户id不能为空");
        }
        User user = baseMapper.selectById(userDTO.getUserId());
        if (user == null) {
            throw new GlobalException("用户信息为空");
        }
        validUniquePhoneNumber(user.getUserId(), userDTO.getPhoneNumber());
        // 记录当前的操作，用于撤销使用
        User oldUser = new User();
        BeanUtils.copyProperties(user, oldUser);
        recordLastHandleMap.put(Constant.editHandle, oldUser);
        recordLastHandleMap.remove(Constant.addHandle);
        recordLastHandleMap.remove(Constant.delHandle);
        Address address = addressService.getById(user.getAddressId());
        if (address != null) {
            address.setProvince(userDTO.getProvince());
            address.setCity(userDTO.getCity());
            address.setDistrict(userDTO.getDistrict());
            address.setDetailAddress(userDTO.getDetailAddress());
            address.setAddressValue(userDTO.getAddressValue());
            if (!addressService.updateById(address)) {
                throw new GlobalException("更新用户地址失败");
            }
        }
        BeanUtils.copyProperties(userDTO, user);
        if (!updateById(user)) {
            throw new GlobalException("编辑用户信息失败");
        }
        return true;
    }

    @Override
    public Boolean delete(List<Integer> asList) {
        // 记录当前的操作，用于撤销使用
        recordLastHandleMap.put(Constant.delHandle, asList);
        recordLastHandleMap.remove(Constant.addHandle);
        recordLastHandleMap.remove(Constant.editHandle);
        return removeBatchByIds(asList);
    }

    @Override
    public Boolean revocation() {
        try {
            User addHandle = (User) recordLastHandleMap.get(Constant.addHandle);
            User editHandle = (User) recordLastHandleMap.get(Constant.editHandle);
            List<Integer> delHandle = (List<Integer>) recordLastHandleMap.get(Constant.delHandle);
            if (addHandle != null) {
                // 撤回新增操作
                removeById(addHandle.getUserId());
                recordLastHandleMap.remove(Constant.addHandle);
            } else if (editHandle != null) {
                // 撤回编辑操作
                updateById(editHandle);
                recordLastHandleMap.remove(Constant.editHandle);
            } else if (delHandle != null && delHandle.size() > 0) {
                // 撤回删除操作
                baseMapper.updateUserByIds(delHandle);
                recordLastHandleMap.remove(Constant.delHandle);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 校验手机号码的唯一性
     */
    private void validUniquePhoneNumber(Integer userId, String phoneNumber) {
        Long exist = baseMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, phoneNumber)
                .ne(userId != null, User::getUserId, userId)
        );
        if (SqlHelper.retBool(exist)) {
            throw new GlobalException("手机号码已存在，请重新添加");
        }
    }

}
